using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using ShareTools.SolutionManagerLibrary;

namespace ShareTools.SolutionManager
{
    public partial class SolutionManager : Form
    {
        List<string> masterList = new List<string>();
        List<WSP> wspList = new List<WSP>();
        List<string> webAppList;
        string msg;
        WSP wspItem;
        TabPage tabExisting;
        TabPage tabNew;

        public SolutionManager()
        {
            InitializeComponent();
            tabControl1.TabPages[0].Text = "Exisitng Solution";
            tabControl1.TabPages[1].Text = "New Solution";
            tabExisting = tabControl1.TabPages[0];
            tabNew = tabControl1.TabPages[1];
            listBoxSolutions.SelectionMode = SelectionMode.MultiExtended;

            Thread procThread = new Thread(new ThreadStart(GetWebApplications));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();
            UpdateWebAppList();
        }

        private void btnExistingSolutions_Click(object sender, EventArgs e)
        {
            txtInformation.Text = "Working.....";
            txtInformation.Update();
            Application.DoEvents();
            Thread procThread = new Thread(new ThreadStart(GetExistingSolutions));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();
            UpdateListItems();
            txtInformation.Text += Environment.NewLine + "Completed";
        }

        private void GetWebApplications()
        {
            Utility util = new Utility();
            webAppList = util.GetWebApplications();
        }

        private void UpdateWebAppList()
        {
            chxListBoxWebApps.Items.AddRange(webAppList.ToArray());
        }

        private void GetExistingSolutions()
        {
            Utility util = new Utility();
            masterList.Clear();
            masterList = util.GetSolutions(false);
        }

        private void UpdateListItems()
        {
            listBoxSolutions.Items.Clear();
            foreach (string solution in masterList)
            {
                if(solution.LastIndexOf("\\") == -1)
                    listBoxSolutions.Items.Add(solution);
                else
                    listBoxSolutions.Items.Add(solution.Substring(solution.LastIndexOf("\\") + 1));
            }
        }

        private void btnClearList_Click(object sender, EventArgs e)
        {
            listBoxSolutions.Items.Clear();
        }

        private void btnRemoveSelected_Click(object sender, EventArgs e)
        {
            if (listBoxSolutions.SelectedItems.Count == 0) return;
            if (listBoxSolutions.SelectedIndex >= 0)
            {
                masterList.RemoveAt(listBoxSolutions.SelectedIndex);
            }
            UpdateListItems();
        }

        private void btnAddNewSolutions_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.Filter = "SharePoint Solution Files (*.wsp)|*.wsp";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = true;
            openFileDialog1.InitialDirectory = @"C:\AdvisorPortal\Tools\ShareInfoPathForms\InfoPathFormsWSPCreator\bin\Debug\Output";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    masterList.Clear();
                    masterList.AddRange(openFileDialog1.FileNames);
                    UpdateListItems();
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    //rchTxtInformation.Text += Environment.NewLine + "Error: Could not read file from disk. Original error: " + ex.Message;
                }
            }
        }

        private void listBoxSolutions_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Utility util = new Utility();
                if (util.IsNewSolution(listBoxSolutions.SelectedItem.ToString()))
                    tabControl1.SelectTab(1); //tabControl1.TabPages[1].Show(); //.Add(tabNew);
                else
                    tabControl1.SelectTab(0); //tabControl1.TabPages[0].Show(); //.Add(tabExisting);
            }
            catch (Exception e1) { }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void btnReDeploy_Click(object sender, EventArgs e)
        {
            if (listBoxSolutions.SelectedItems.Count == 0) return;
            if (listBoxSolutions.SelectedItem.ToString().ToLower() != txtNewWSPLocation.Text.Substring(txtNewWSPLocation.Text.LastIndexOf("\\") + 1).ToLower())
            {
                MessageBox.Show("The WSP file name doesnt match with your selection. Please select the correct one.");
                return;
            }
            tabControl1.SelectTab(1);
        }

        private void chxIsAllUrls_CheckedChanged(object sender, EventArgs e)
        {
            if (chxIsAllUrls.Checked)
            {
                for (int i = 0; i < chxListBoxWebApps.Items.Count; i++)
                    chxListBoxWebApps.SetItemChecked(i, true);
                chxListBoxWebApps.Enabled = false;
            }
            else
                chxListBoxWebApps.Enabled = true;
        }

        private void chxImmediateDeployment2_CheckedChanged(object sender, EventArgs e)
        {
            if (chxImmediateDeployment2.Checked)
            {
                txtDeploymentTime2.Text = "";
                txtDeploymentTime2.Enabled = false;
            }
            else
                txtDeploymentTime2.Enabled = true;
        }

        private void chxImmediateDeployment1_CheckedChanged(object sender, EventArgs e)
        {
            if (chxImmediateDeployment1.Checked)
            {
                txtUpgradeTime.Text = "";
                txtUpgradeTime.Enabled = false;
            }
            else
                txtUpgradeTime.Enabled = true;
        }

        private void btnDeploySolution_Click(object sender, EventArgs e)
        {
            if (listBoxSolutions.SelectedItems.Count == 0) return;
            Utility util = new Utility();
            if (util.IsNewSolution(listBoxSolutions.SelectedItem.ToString()))
                DeployWSP(false);
            else
                DeployWSP(true);
        }

        private void DeployWSP(bool isReDeployment)
        {
            if (listBoxSolutions.Items.Count == 0 || listBoxSolutions.SelectedItems.Count == 0) return;

            if (!isReDeployment && masterList[listBoxSolutions.SelectedIndex].IndexOf("\\") == -1)
            {
                MessageBox.Show("If you are trying to redeploy existing solution, go to 'Existing Solutin' tab and provide the latest solution path and hit 'Redeploy'");
                return;
            }
            if (isReDeployment && listBoxSolutions.SelectedItem.ToString().ToLower() != txtNewWSPLocation.Text.Substring(txtNewWSPLocation.Text.LastIndexOf("\\") + 1).ToLower())
            {
                MessageBox.Show("The New WSP file name doesnt match with your selection. Go to the existing tab and please select the correct one.");
                return;
            }
            if (!chxImmediateDeployment2.Checked && string.IsNullOrEmpty(txtDeploymentTime2.Text.Trim()))
            {
                MessageBox.Show("Please select either immediate option or specify time");
                return;
            }

            DateTime tmpDt;
            if (!chxImmediateDeployment2.Checked)
            {
                if (!DateTime.TryParse(txtDeploymentTime2.Text.Trim(), out tmpDt))
                {
                    MessageBox.Show("Date time format is incorrect"); return;
                }
            }

            msg = string.Empty;
            WSP wsp = new WSP();
            wsp.Name = listBoxSolutions.SelectedItem.ToString();
            wsp.Location = isReDeployment ? txtNewWSPLocation.Text.Trim() : masterList[listBoxSolutions.SelectedIndex];
            wsp.IsImmediate = chxImmediateDeployment2.Checked ? true : false;
            wsp.IsGACDeploymentAllowed = chxIsGacDeploymentAllowed.Checked ? true : false;
            wsp.IsForced = chxIsForce.Checked ? true : false;
            wsp.TimeToDeploy = wsp.IsImmediate ? DateTime.Now : Convert.ToDateTime(txtDeploymentTime2.Text);
            if (chxIsAllUrls.Checked)
            {
                wsp.UrlList = webAppList;
            }
            else
            {
                foreach (object item in chxListBoxWebApps.CheckedItems)
                {
                    wsp.UrlList.Add(item.ToString());
                }
                //for (int i = 0; i < chxListBoxWebApps.CheckedItems.Count; i++)
                  //  wsp.UrlList.Add(chxListBoxWebApps.se .CheckedItems[i].ToString());
            }
            wspItem = wsp;
            txtInformation.Text = "Deploying.....";
            txtInformation.Update();
            Application.DoEvents();
            Thread procThread = new Thread(new ThreadStart(DeploymentProcess));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();
            
            txtInformation.Text += Environment.NewLine + (string.IsNullOrEmpty(msg)? "Completed" : msg);
        }

        private void DeploymentProcess()
        {

            Utility util = new Utility();
            try
            {
                util.DeploySolution(wspItem);
            }
            catch (Exception e1)
            {
                msg = e1.ToString();
            }
        }

        //Select new wsp for redeployment
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.Filter = "SharePoint Solution Files (*.wsp)|*.wsp";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = false;
            openFileDialog1.InitialDirectory = @"C:\AdvisorPortal\Tools\ShareInfoPathForms\InfoPathFormsWSPCreator\bin\Debug\Output";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    txtNewWSPLocation.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    //rchTxtInformation.Text += Environment.NewLine + "Error: Could not read file from disk. Original error: " + ex.Message;
                }
            }
        }

        private void btnUpgrade_Click(object sender, EventArgs e)
        {
            if (listBoxSolutions.SelectedItems.Count == 0) return;

            if (!chxImmediateDeployment1.Checked && string.IsNullOrEmpty(txtUpgradeTime.Text))
            {
                MessageBox.Show("Please provide the upgrade time."); return;
            }
            DateTime tmpDt;
            if (!chxImmediateDeployment1.Checked && !DateTime.TryParse(txtUpgradeTime.Text, out tmpDt))
            {
                MessageBox.Show("Upgrade time format is incorrect"); return;
            }
            if (listBoxSolutions.SelectedItem.ToString().ToLower() != txtNewWSPLocationForUpgrade.Text.ToLower().Substring(txtNewWSPLocationForUpgrade.Text.LastIndexOf("\\") + 1))
            {
                MessageBox.Show("The new WSP file name doesnt match with your selection. Please select the correct one.");  return;
            }

            msg = string.Empty;
            WSP wsp = new WSP();
            wsp.Name = listBoxSolutions.SelectedItem.ToString();
            wsp.Location = txtNewWSPLocationForUpgrade.Text.Trim();
            wsp.IsImmediate = chxImmediateDeployment1.Checked ? true : false;
            wsp.TimeToDeploy = wsp.IsImmediate ? DateTime.Now : Convert.ToDateTime(txtUpgradeTime.Text);
            wspItem = wsp;
            txtInformation.Text = "Upgrading.....";
            txtInformation.Update();
            Application.DoEvents();
            Thread procThread = new Thread(new ThreadStart(UpgradeProcess));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();

            txtInformation.Text += Environment.NewLine + (string.IsNullOrEmpty(msg) ? "Completed" : msg);

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.Filter = "SharePoint Solution Files (*.wsp)|*.wsp";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = false;
            openFileDialog1.InitialDirectory = @"C:\AdvisorPortal\Tools\ShareInfoPathForms\InfoPathFormsWSPCreator\bin\Debug\Output";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    txtNewWSPLocationForUpgrade.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                    //rchTxtInformation.Text += Environment.NewLine + "Error: Could not read file from disk. Original error: " + ex.Message;
                }
            }
        }

        private void UpgradeProcess()
        {
            Utility util = new Utility();
            try
            {
                util.UpgradeSolution(wspItem);
            }
            catch (Exception e1)
            {
                msg = e1.ToString();
            }
        }

        private void btnRemoveSolution_Click(object sender, EventArgs e)
        {
            if (listBoxSolutions.SelectedItems.Count == 0) return;
            msg = string.Empty;
            WSP wsp = null;
            foreach (object item in listBoxSolutions.SelectedItems)
            {
                
            }
            wsp = new WSP();
            wsp.Name = listBoxSolutions.SelectedItem.ToString();
            wspItem = wsp;
            txtInformation.Text = "Removing the solution.....";
            txtInformation.Update();
            Application.DoEvents();
            Thread procThread = new Thread(new ThreadStart(RemoveProcess));
            procThread.IsBackground = true;
            procThread.Start();
            procThread.Join();

            txtInformation.Text += Environment.NewLine + (string.IsNullOrEmpty(msg) ? "Completed" : msg);
        }

        private void RemoveProcess()
        {
            try
            {
                Utility util = new Utility();
                util.RemoveSolution(wspItem);
            }
            catch(Exception e1)
            {
                msg = e1.ToString();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void btnExecJobs_Click(object sender, EventArgs e)
        {
            Utility util = new Utility();
            txtInformation.Text = "Started executing the administrative service timer jobs....";
            txtInformation.Update();
            util.ExecuteJobDefinitions();
            txtInformation.Text += Environment.NewLine + "Completed";
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            About abt = new About();
            abt.ShowDialog();
        }

        private void chxSelectAllForRemoving_CheckedChanged(object sender, EventArgs e)
        {
            //listBoxSolutions.se
        }

    }
}